import axios from "axios";
// import { message } from "antd";
import storage from "./storage";

const api = import.meta.env.VITE_BASE_URL;

const instance = axios.create({
  baseURL: api,
  timeout: 3000,
  timeoutErrorMessage: "网络请求超时",
  withCredentials: true, // 允许携带cookie
  headers: {
    "Content-Type": "application/json;",
    "X-Requested-With": "XMLHttpRequest",
    Authorization: "Bearer " + storage.get("token"),
  }
});

instance.interceptors.request.use( 
  (config) => {
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

instance.interceptors.response.use( 
  (response) => {
    const res = response.data;
    if (res.code === 40001) { // 未登录状态码
       window.location.href = "/login";
    } else if (res.code !== 200 ){
      //  message.error(res.msg);
      return res.data;
    }
    return res.data;
  },
  (error) => {
    return Promise.reject(error);
}
)
export default {
    get<T>(url:string, params?:object):Promise<T>{return instance.get(url, {params})},
    post<T>(url:string, data?:object):Promise<T>{return instance.post(url, data)},
    put<T>(url:string, data?:object):Promise<T>{return instance.put(url, data)},
    delete<T>(url:string,params?:object):Promise<T>{return instance.delete(url,{params})},
};